package com.platform.tony.config;


import com.platform.tony.dto.UserDto;
import com.platform.tony.entity.User;
import com.platform.tony.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

@Slf4j
public class WeChatAuthProvider implements AuthenticationProvider {

    private UserService userService;

    public WeChatAuthProvider(UserService userService) {
        this.userService = userService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        WeChatAuthToken token = (WeChatAuthToken) authentication;

        String openId = token.getOpenId();
        log.info("start to authenticate {} ...", openId);

        UserDto loadedUser = null;
        try {
            User user = this.userService.queryUserInfo(openId);
            // todo
            loadedUser = new UserDto();


        } catch (UsernameNotFoundException notFound) {
            throw notFound;
        } catch (Exception exception) {
            throw new InternalAuthenticationServiceException(exception.getMessage(), exception);
        }

        token.setPrincipal(loadedUser);
        token.setDetails(loadedUser);
        token.setAuthorities(loadedUser.getAuthorities());
        authentication.setAuthenticated(true);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return authentication;

    }

    /**
     * 微信登录方式
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(WeChatAuthToken.class);
    }
}
